#!/usr/bin/env Rscript
args = commandArgs(trailingOnly=TRUE)

source("cueing_functions.R")

cocs <- as.numeric(args[1])
oppcs <- as.numeric(args[2])

# Get median
hx <- read.csv("hpolarization.csv")
sx <- read.csv("spolarization.csv")

x <- read.csv(paste0("cueing_data1616split.csv"))
x$polar <- 0
for (c in unique(x$congress)){
  x$polar[which(x$chamber == "house" & x$congress == c)] <- hx$difference[which(hx$congress == c)]
  x$polar[which(x$chamber == "senate" & x$congress == c)] <- sx$difference[which(sx$congress == c)]
}

polarmedh <- median(x$polar[which(x$chamber == "house")])
polarmeds <- median(x$polar[which(x$chamber == "senate")])

# Run analysis
x <- read.csv(paste0("cueing_data1616splitweighted.csv"))
x$deltay <- (x$agree2 - x$agree1)
x$friend <- apply(cbind(x$copartisans, x$cs), 1, 
                  function(z) ifelse(z[1] == 1, ifelse(z[2] >= cocs, 1, 0), 
                                     ifelse(z[2] >= oppcs, 1, 0)))

x$polar <- 0
for (c in unique(x$congress)){
  x$polar[which(x$chamber == "house" & x$congress == c)] <- ifelse(hx$difference[which(hx$congress == c)] >= polarmedh, 1, 0)
  x$polar[which(x$chamber == "senate" & x$congress == c)] <- ifelse(sx$difference[which(sx$congress == c)] >= polarmeds, 1, 0)
}

x$legA2 <- apply(x, 1, function(z) paste0(z[16], z[7]))
x$legB2 <- apply(x, 1, function(z) paste0(z[17], z[7]))

Aind <- which(colnames(x) == "legA2")
Bind <- which(colnames(x) == "legB2")

x$dyads <- apply(x, 1, function(r) paste0(r[Aind], "-", r[Bind]))

fmla <- formula(deltay ~ -1 + treat + friend + 
                  I(treat * polar) + I(friend * polar) +
                  I(treat * friend * polar) + 
                  I(treat * friend * (1-polar)) +
                  I(treat * copartisans) + 
                  I(friend * copartisans) + 
                  sgcs + I(treat * sgcs) +
                  ogcs + I(treat * ogcs) + 
                  sfcs + I(treat * sfcs) + 
                  ofcs + I(treat * ofcs) +
                  interaction(factor(congress), committee,
                              leg_party, copartisans) + 
                  n1 + n2)

fit <- lm(fmla, data = x, weights = x$weights)
coef(fit)[1:16]
coef(fit)[1:16]/sqrt(diag(vcov(fit))[1:16])

index <- unique(c(as.character(x$legA2), as.character(x$legB2)))

dyad.mat <- apply(x[,c(Aind, Bind)], 2, as.character)
cl <- makeCluster(32)
registerDoSNOW(cl)
dyad.vcov <- dyad.robust.se(x, fit, index, dyad.mat)
stopCluster(cl)

fit <- lm(fmla, data = x, weights = x$weights, qr = FALSE)
save.image(paste0("polar_cueingresults_", cocs, oppcs, ".RData"))
